﻿#region

using System;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.MSBuild;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.CSharp.SyntaxKind;

#endregion

namespace HearthDb.CardIdGenerator
{
	internal class Program
	{
		private const string File = "../../../HearthDb/CardIds.cs";

		static void Main()
		{
			var @namespace = NamespaceDeclaration(IdentifierName("HearthDb"));
			var header = ParseLeadingTrivia(@"/* THIS CLASS WAS GENERATED BY HearthDb.CardIdGenerator. DO NOT EDIT. */");
			var cCardIds = ClassDeclaration("CardIds").AddModifiers(Token(PublicKeyword)).WithLeadingTrivia(header);

			Console.WriteLine("Generating collectible cards...");
			var cCollectible = SyntaxBuilder.GetCollectible();

			Console.WriteLine("Generating non-collectible cards...");
			var cNonCollectible = SyntaxBuilder.GetNonCollectible();

			Console.WriteLine("Adding cards to namespace...");
			cCardIds = cCardIds.AddMembers(cCollectible);
			cCardIds = cCardIds.AddMembers(cNonCollectible);
			@namespace = @namespace.AddMembers(cCardIds);
		
			Console.WriteLine("Formatting namespace. This may take a while...");
			var root = Formatter.Format(@namespace, MSBuildWorkspace.Create());

			var rootString = root.ToString();
			string prevString;
			using (var sr = new StreamReader(File))
				prevString = sr.ReadToEnd();

			if (prevString != rootString)
			{
				Console.WriteLine($"Saving to '{File}'...");
				using(var sr = new StreamWriter(File))
					sr.Write(root.ToString());

				Console.WriteLine("Done. Press any key to exit.");
			}
			else
				Console.WriteLine($"No changes. Press any key to exit.");

			Console.ReadKey();
		}
	}
}